// 是否为数组
const isArray = (value) => {
  if (typeof Array.isArray === "function") {
    return Array.isArray(value);
  } else {
    return Object.prototype.toString.call(value) === "[object Array]";
  }
}

// 是否为数字
const isNumber = (value) => {
  var re = /^[0-9]+.?[0-9]*/
  return re.test(value)
}

// 对Date的扩展，将 Date 转化为指定格式的String   
// 月(M)、日(d)、小时(H)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，   
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   
// 例子：   
// (new Date()).Format("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423   
// (new Date()).Format("yyyy-M-d H:m:s.S")      ==> 2006-7-2 8:9:4.18   
Date.prototype.Format = function(fmt)   
{ //author: meizz   
  var o = {   
    "M+" : this.getMonth()+1,                 //月份   
    "d+" : this.getDate(),                    //日   
    "H+" : this.getHours(),                   //小时   
    "m+" : this.getMinutes(),                 //分   
    "s+" : this.getSeconds(),                 //秒   
    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
    "S"  : this.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
}

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatDate(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  return [year, month, day].map(formatNumber).join('-') 
}

// 两个日期之间相差的天数
const daysBetween = (dateStrFrom,dateStrTo) => {
  let startDate = Date.parse(dateStrFrom)
  if(isEmpty(startDate)){
    // IOS只识别2017/01/01这样的日期格式
    if(!isEmpty(dateStrFrom)){
      startDate = new Date(dateStrFrom.replace(/-/g, '/'))
    }
  }

  let endDate = Date.parse(dateStrTo)
  if(isEmpty(endDate)){
    if(!isEmpty(dateStrTo)){
      endDate = new Date(dateStrTo.replace(/-/g, '/'))
    }
  }

  if (startDate>endDate){
      return 0
  }
  if (startDate==endDate){
      return 1
  }
  var days=(endDate - startDate)/(1*24*60*60*1000)
  return  days
}

/*
判断是否为空。
注意:空白字符串不是空
*/
const isEmpty = function (param) {
  if (typeof param == "object") {
    /* 是否为数组 */
    if ((param == null) || (isArray(param) && param.length == 0) || (param.hasOwnProperty('length') && param.length == 0)) {
      return true;
    }
    for (var name in param) {
      return false;
    }
    return true;
  }
  return typeof param == "undefined" || typeof param == "string" && (param == "") || typeof param == "number" && isNaN(param);
}

/**
 * request普通封装
 * <p>
 * 注意:
 * 如果需要向后台提交json格式的数据请自己获取token，调用wx.request
 */
function wxRequest(opts) {
  let token = wx.getStorageSync('token')
  
  // 为post提交添加Header，参数作为表单提交，后台可以通过request.getParameter(key)获取参数
  let method = opts.method
  if (isEmpty(method)) {
    method = 'get'
    opts.method = method
  }
  if ('post' === method.toLowerCase()) {
    if (opts.header) {
      // 提交json的处理
      const contentType = opts.header['content-type']
      
      if(!isEmpty(contentType) && contentType.indexOf('application/json') != -1){
        opts.header['content-type'] = 'application/json;charset=UTF-8'
      }else{
        opts.header['content-type'] = 'application/x-www-form-urlencoded'
      }
      opts.header['X-Wds-Token'] = token
    } else {
      opts.header = {
        'content-type': 'application/x-www-form-urlencoded',
        'X-Wds-Token': token
      }
    }
  }else if('get' === method.toLowerCase()){
    opts.header = {
      'X-Wds-Token': token
    }
  }

  let success = opts.success
  let newsuccess = (res) => {
  
    if (res.data.statusCode == 401 || res.data.statusCode == 403) {
      // 清除登录相关内容
      try {
        wx.removeStorageSync('token')
        wx.removeStorageSync('userInfo')
        wx.removeStorageSync('enterpriseId')
        wx.removeStorageSync('enterpriseName')
        wx.removeStorageSync('placeId')
        wx.removeStorageSync('placeName')
        
        wx.removeStorageSync('choosed_date')
      } catch (e) {
        // Do something when catch error
      }
      
      wx.navigateTo({
        url: '/pages/auth/login/login'
      })
      return
    }

    // 执行原本的success
    success(res) 
  }
  opts.success = newsuccess

  let failFun = opts.fail
  let newFail = (err) => {
    // 根据微信官方文档,这里无法获取http状态码

    // 执行原本的fail
    if(failFun){
      failFun(err)
    }
  }
  opts.fail = newFail

  wx.request(opts)
}

/**
 * Promise封装微信的的request
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function(resolve, reject) {
    wxRequest({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Wds-Token': wx.getStorageSync('token')
      },
      success: function(res) {
        if (res.statusCode == 200) {
          if (res.data.statusCode == 401 || res.data.statusCode == 403) {
            // 清除登录相关内容
            try {
              wx.removeStorageSync('token')
              wx.removeStorageSync('userInfo')
              wx.removeStorageSync('enterpriseId')
              wx.removeStorageSync('enterpriseName')
              wx.removeStorageSync('placeId')
              wx.removeStorageSync('placeName')
              
              wx.removeStorageSync('choosed_date')
            } catch (e) {
              // Do something when catch error
            }
            
            wx.navigateTo({
              url: '/pages/auth/login/login'
            })
          }else{
            resolve(res.data)
          }
        } else {
          reject(res.errMsg)
        }
      },
      fail: function(err) {
        reject(err)
      }
    })
  })
}

//返回上一级页面
const navigatePrev = () => {
  let pages = getCurrentPages();
  let prevPage = pages[pages.length - 2];
  console.log('prevPage.route:' + prevPage.route)

  if (!isEmpty(prevPage)) {
    // 如果是登录页面跳转过来的，则需要返回上上个页面
    if ('pages/auth/login/login' === prevPage.route){
      wx.navigateBack({
        delta: 2
      })
    }else{
      wx.navigateBack({
        delta: 1
      })
    }
  } else {
    // 跳转首页
    wx.reLaunch({
      url: '/pages/index/index'
    })
  }
}

const showToast = msg => {
  wx.showToast({
    title: msg,
    icon: 'none',
    mask: true,
    duration: 2000
  })
}

const showSuccessToast = msg => {
  wx.showToast({
    title: msg,
    icon: 'success',
    duration: 2000
  })
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/assets/images/icon_error.png'
  })
}

// 获取url参数 
function getQueryString(url, name) {
  var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
  var r = url.substr(1).match(reg)
  if (r != null) {
    return r[2]
  }
  return null;
}

function previewImage(image) {
  if (!isEmpty(image)) {
    let urls = []
    urls.push(image)
    wx.previewImage({
      image,
      urls
    })
  }else{
    console.log('image url can not be empty')
  }
}

const getStorageSync = (key) => {
  let value
  try {
    value = wx.getStorageSync(key)
  } catch (e) {
    value = ''
    console.log('wx.getStorageSync ERR',e)
  }
  return value
}

function previewFile(fileUrl){
  if (!isEmpty(fileUrl)) {
    wx.showLoading({ title: '' })
    wx.downloadFile({
      url: fileUrl,
      success(res) {
        const filePath = res.tempFilePath
        setTimeout(() => {
          wx.openDocument({
            filePath,
            success(res) {
              console.log('openDocument success')
              wx.hideLoading()
            }, fail(res) {
              console.log('openDocument fail')
              wx.hideLoading()
            }
          })
        }, 1000)
      }, fail(res) {
        console.log('downloadFile fail')
        wx.hideLoading()
      }
    })
  }else{
    console.log('file url can not be empty')
  }
}

module.exports = {
  isArray,
  isNumber,
  isEmpty,
  
  formatTime,
  formatDate,
  daysBetween,
  
  wxRequest,
  request,
  getQueryString,
  
  showToast,
  showSuccessToast,
  showErrorToast,
  
  navigatePrev,
  previewImage,
  previewFile,
  getStorageSync
}